package com.ruoyi.system.bargain.controller;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.operation.service.IOperationHistoryService;
import com.ruoyi.system.bargain.domain.PanZhiBargainReq;
import com.ruoyi.system.bargain.domain.PangXieBargainReq;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.model.domain.OperationHistory;
import com.ruoyi.system.model.domain.SalePartner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @other pzz
 * @data 2024/8/31
 * @apiNote
 */
@Slf4j
@RestController
@RequestMapping("/business/panzhi/bargain")
public class PanZhiBargainSaleController extends BaseController {
    @Resource
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private IOperationHistoryService operationHistoryService;
    @Autowired
    private RedisCache redisCache;
    static String TOKEN_PANZHI = "";

    @PostMapping("/list")
    public AjaxResult list(@RequestBody PanZhiBargainReq req) {
        return AjaxResult.success();
//        String url ="https://api.pzds.com/api/web-client/v3/bargain/seller/list";
//        getToken();
//        JSONObject params = new JSONObject();
//        JSONObject action = new JSONObject();
//        action.put("bargainOrderNo",req.getBargainOrderNo());
//        action.put("goodsNo",req.getGoodsNo());
////        //     * 状态
////        //     * BUYER_QUOTATION 待处理
////        //     * BUYER_QUOTATION_AGAIN 二次出价
////        //     * SELLER_COUNTER_OFFER 已还价
////        //     * SELLER_AGREE 已同意
////        //     * BUYER_AGREE 买家同意
////        //     * null 全部
////        String status = null;
////        if (StringUtils.isEmpty(req.getStatus())){
////        }else if (StringUtils.equals(req.getStatus(),"BUYER_QUOTATION")){
////            status = "";
////        }
//
//        action.put("status",req.getStatus());
//        params.put("action",action);
//        params.put("page",req.getPage());
//        params.put("pageSize",req.getPageSize());
//
//        String response = getPanZhi(url,params);
//        System.out.println(response);
//        return AjaxResult.success(JSONObject.parseObject(response).getJSONObject("data"));
    }

    @PostMapping("/bargainBack")
    public AjaxResult bargainBack(@RequestBody PanZhiBargainReq req) {
        String url = "https://api.pzds.com/api/web-client/v2/bargain/counter";
        getToken();
        JSONObject params = new JSONObject();
        JSONObject action = new JSONObject();
        action.put("id",req.getId());
        action.put("sellerPrice",req.getSellerPrice());
        params.put("action",action);
        String response = getPanZhi(url,params);
        setOper("盼之砍价","商品id:"+req.getId() +"  还价"+req.getSellerPrice() );
        System.out.println(response);
        return AjaxResult.success(JSONObject.parseObject(response));
    }

    /**
     * 拒绝
     * @param req
     * @return
     */
    @PostMapping("/refuse")
    public AjaxResult refuse(@RequestBody PanZhiBargainReq req) {
        String url = "https://api.pzds.com/api/web-client/v2//bargain/refuse";
        getToken();
        JSONObject params = new JSONObject();
        JSONObject action = new JSONObject();
        action.put("id",req.getId());
        action.put("agreeStatus",req.getSellerPrice());
        params.put("action",action);
        String response = getPanZhi(url,params);
        System.out.println(response);
        setOper("盼之砍价拒绝","商品id:"+req.getId() );

        return AjaxResult.success(JSONObject.parseObject(response));
    }

    /**
     * 成功
     * @param req
     * @return
     */
    @PostMapping("/agree")
    public AjaxResult deal(@RequestBody PanZhiBargainReq req) {
        String url = "https://api.pzds.com/api/web-client/v2//bargain/agree";
        getToken();
        JSONObject params = new JSONObject();
        JSONObject action = new JSONObject();
        action.put("id",req.getId());
        action.put("agreeStatus",req.getSellerPrice());
        params.put("action",action);
        String response = getPanZhi(url,params);
        System.out.println(response);
        setOper("盼之砍价同意","商品id:"+req.getId() );

        return AjaxResult.success(JSONObject.parseObject(response));
    }

    public void getToken() {
        String token = (String) redisCache.getCacheObject("PANZHI_BARGAIN_TOKEN");
        if (StringUtils.isNotEmpty(token)) {
            TOKEN_PANZHI = token;
            return;
        }
        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataByType("panzhi_bargainBack");
        String username="";
        String password="";
        for (SysDictData dictData : sysDictDataList) {
            if ("username".equals(dictData.getDictLabel())) {
                username=  dictData.getDictValue();
            }
            if ("password".equals(dictData.getDictLabel())) {
                password =  dictData.getDictValue();
            }
        }
        token = loginPanzhi(username, password);
        if (StringUtils.isNotEmpty(token)) {
            TOKEN_PANZHI = token;
            redisCache.setCacheObject("PANZHI_BARGAIN_TOKEN", token, 3, TimeUnit.MINUTES);
        }
    }
    public String getPanZhi(String url,JSONObject params){

        String paramsStr = JSONObject.toJSONString(params);
        log.info("盼之新增请求参数={}", paramsStr);
        // 生成 随机数 并生成sign  注意 &2147483647         &accessKey=3qXyB7uf
        StringBuilder sb = new StringBuilder();
        long PZTimestamp = System.currentTimeMillis();
        String Random = getRanString();
        sb.append("PZTimestamp=");
        sb.append(PZTimestamp);
        sb.append("&Random=");
        sb.append(Random);
        sb.append("&2147483647=");
        sb.append(JSONObject.toJSON(params));
        sb.append("&accessKey=3qXyB7uf");
        System.out.println(sb.toString());
        String b = sb.toString();
        try {
            b = URLEncoder.encode(b, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        b = b.replace("%26", "&");
        b = b.replace("%3D", "=");
        System.out.println(b);
        b = b.replaceAll("\\(", "%28");
        b = b.replaceAll("\\)", "%29");
        b = b.replaceAll("'", "%27");
        b = b.replaceAll("\\*", "%2A");
        b = b.replaceAll("~", "%7E");
        b = b.replaceAll("!|！", "%21");
        b = b.replaceAll("\\+", "%20");
        System.out.println(b);
        String sign = DigestUtils.md5Hex(b);
        System.out.println(sign);
        //开始拼装请求
        String response = HttpRequest.post(url)
                .header("Accept", "application/json, text/plain, */*")
                .header("PZTimestamp", String.valueOf(PZTimestamp))
                .header("Content-Type", "application/json;charset=UTF-8")
                .header("Origin", "https://www.pzds.com")
                .header("PZPlatform", "pc")
                .header("PZVersion", "1.0.0")
                .header("PZVersionCode", "1")
                .header("Random", Random)
                .header("Referer", "https://www.pzds.com/")
                .header("sign", sign)
                .header("Token", TOKEN_PANZHI)
                .header("sec-ch-ua-mobile", "?0")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like " +
                        "Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123 .0.0.0")
                .body(JSONObject.toJSONString(params)).execute().body();
        log.info("盼之新增返回参数={}", response);
        return  response;
    }

    public String loginPanzhi(String userName, String pwd) {
        String url = "https://api.pzds.com/api/web-client/v2/user/public/login/password";
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> action = new HashMap<>();
        params.put("phone", userName);
        String string = DigestUtils.md5Hex(pwd);
        params.put("password", string);
        params.put("openId", null);
        params.put("thirdType", null);
        params.put("unionId", null);
        action.put("action", params);

        // 生成 随机数 并生成sign  注意 &2147483647         &accessKey=3qXyB7uf
        StringBuilder sb = new StringBuilder();
        long PZTimestamp = System.currentTimeMillis();
        String Random = getRanString();
        sb.append("PZTimestamp=");
        sb.append(PZTimestamp);
        sb.append("&Random=");
        sb.append(Random);
        sb.append("&2147483647=");
        sb.append(JSONObject.toJSON(action));
        sb.append("&accessKey=3qXyB7uf");
        System.out.println(sb.toString());
        String b = sb.toString();
        try {
            b = URLEncoder.encode(b, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        b = b.replace("%26", "&");
        b = b.replace("%3D", "=");
        b = b.replaceAll("\\(", "%28");
        b = b.replaceAll("\\)", "%29");
        b = b.replaceAll("'", "%27");
        b = b.replaceAll("\\*", "%2A");
        b = b.replaceAll("~", "%7E");
        b = b.replaceAll("!|！", "%21");
        String sign = DigestUtils.md5Hex(b);
        //开始拼装请求
        String body = HttpRequest.post(url).header("Accept", "application/json, text/plain, */*")
                .header("PZTimestamp", String.valueOf(PZTimestamp))
                .header("Content-Type", "application/json;charset=UTF-8")
                .header("Origin", "https://www.pzds.com")
                .header("PZPlatform", "pc")
                .header("PZVersion", "1.0.0")
                .header("PZVersionCode", "1")
                .header("Random", Random)
                .header("Referer", "https://www.pzds.com/")
                .header("sign", sign)
                .header("sec-ch-ua-mobile", "?0")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like " +
                        "Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123 .0.0.0")
                .body(JSONObject.toJSONString(action)).execute().body();
        return JSONObject.parseObject(body).getString("data");
    }

    public static String getRanString() {
        Random random = new Random();
        //把随机生成的数字转成字符串
        String str = String.valueOf(random.nextInt(9));
        for (int i = 0; i < 5; i++) {
            str += random.nextInt(9);
        }
        if (str.startsWith("0")) {
            str = str.replaceFirst("0", "1");
        }
        return str;
    }


    //操作记录
    private void setOper(String operation,String reason) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        OperationHistory operationHistory = new OperationHistory();
        operationHistory.setOperator(loginUser.getUsername());
        operationHistory.setOperatTime(new Date());
        operationHistory.setStatus(operation);
        operationHistory.setReason(reason);
        operationHistoryService.insertOperationHistory(operationHistory);
    }
}
